//
//  PhotographViewController.m
//  SelfDriving
//
//  Created by apple on 16/2/2.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "PhotographViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "PhotographCompleteVC.h"
@interface PhotographViewController ()<AVCaptureMetadataOutputObjectsDelegate>
@property ( strong , nonatomic ) AVCaptureDevice * device;
@property ( strong , nonatomic ) AVCaptureDeviceInput * input;
@property ( strong , nonatomic ) AVCaptureStillImageOutput * output;
@property ( strong , nonatomic ) AVCaptureSession * session;
@property ( strong , nonatomic ) AVCaptureVideoPreviewLayer * preview;
@property (strong, nonatomic) UIImageView *scanLayer;
@property (strong,nonatomic)UIImagePickerController * imagePikerViewController;

@end

@implementation PhotographViewController

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleDefault;
    //UIStatusBarStyleDefault = 0 黑色文字，浅色背景时使用
    //UIStatusBarStyleLightContent = 1 白色文字，深色背景时使用
}
- (BOOL)prefersStatusBarHidden
{
    return YES; //返回NO表示要显示，返回YES将hiden
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(viewwilizp:)
     name:@"viewwilizp"
     object:nil];
    
    [self setNeedsStatusBarAppearanceUpdate];
    [self initView];

}

#pragma mark 刷新照片UI
-(void)viewwilizp:(UIButton *)btn{
    [ _session startRunning ];
}
-(void)initView{
    // Device
    _device = [ AVCaptureDevice defaultDeviceWithMediaType : AVMediaTypeVideo ];
    // Input
    NSError *error = nil;
    _input = [ AVCaptureDeviceInput deviceInputWithDevice : self . device error : &error];
    // Output
    _output = [[AVCaptureStillImageOutput alloc] init];
    NSDictionary * outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG,AVVideoCodecKey, nil];
    //这是输出流的设置参数AVVideoCodecJPEG参数表示以JPEG的图片格式输出图片
    [_output setOutputSettings:outputSettings];
    // Session
    _session = [[ AVCaptureSession alloc ] init ];
    [ _session setSessionPreset : AVCaptureSessionPresetHigh ];
    if ([ _session canAddInput : self . input ])
    {
        [ _session addInput : self . input ];
    }
    if ([ _session canAddOutput : self . output ])
    {
        [ _session addOutput : self . output ];
    }
    NSString *mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"相机启动失败" message:@"请为一米开放相机权限，手机设置->隐私->相机->一米->打开" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    // Preview
    _preview =[ AVCaptureVideoPreviewLayer layerWithSession : _session ];
    _preview . videoGravity = AVLayerVideoGravityResizeAspectFill ;
    _preview . frame = self.view.frame;
    [ self . view . layer insertSublayer : _preview atIndex : 0 ];
    [ _session startRunning ];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)qiehuanAction:(UIButton *)sender {
    NSUInteger cameraCount = [[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] count];
    if (cameraCount > 1) {
        NSError *error;
        AVCaptureDeviceInput *newVideoInput;
        AVCaptureDevicePosition position = [[_input device] position];
        
        if (position == AVCaptureDevicePositionBack)
            newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:[self frontCamera] error:&error];
        else if (position == AVCaptureDevicePositionFront)
            newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:[self backCamera] error:&error];
        else
            return;
        
        if (newVideoInput != nil) {
            [self.session beginConfiguration];
            [self.session removeInput:_input];
            if ([self.session canAddInput:newVideoInput]) {
                [self.session addInput:newVideoInput];
                [self setInput:newVideoInput];
            } else {
                [self.session addInput:_input];
            }
            [self.session commitConfiguration];
        } else if (error) {
            NSLog(@"toggle carema failed, error = %@", error);
        }
    }
    
    
}
- (IBAction)shanguangdengAction:(UIButton *)sender {
    
    BOOL con1 = [_device hasTorch];    //支持手电筒模式
    BOOL con2 = [_device hasFlash];    //支持闪光模式
    
    if (con1 && con2)
    {
        [self changeDevicePropertySafety:^(AVCaptureDevice *captureDevice) {
            if (_device.flashMode == AVCaptureFlashModeOn)         //闪光灯开
            {
                [_device setFlashMode:AVCaptureFlashModeOff];
                [_device setTorchMode:AVCaptureTorchModeOff];
            }else if (_device.flashMode == AVCaptureFlashModeOff)  //闪光灯关
            {
                [_device setFlashMode:AVCaptureFlashModeOn];
                [_device setTorchMode:AVCaptureTorchModeOn];
            }
            //            else{                                                      //闪光灯自动
            //                [_videoDevice setFlashMode:AVCaptureFlashModeAuto];
            //                [_videoDevice setTorchMode:AVCaptureTorchModeAuto];
            //            }
//            NSLog(@"现在的闪光模式是AVCaptureFlashModeOn么?是你就扣1, %zd",_device.flashMode == AVCaptureFlashModeOn);
        }];
        sender.selected=!sender.isSelected;
    }else{
        NSLog(@"不能切换闪光模式");
    }
}
//更改设备属性前一定要锁上
-(void)changeDevicePropertySafety:(void (^)(AVCaptureDevice *captureDevice))propertyChange{
    //也可以直接用_videoDevice,但是下面这种更好
    AVCaptureDevice *captureDevice= [_input device];
    NSError *error;
    //注意改变设备属性前一定要首先调用lockForConfiguration:调用完之后使用unlockForConfiguration方法解锁,意义是---进行修改期间,先锁定,防止多处同时修改
    BOOL lockAcquired = [captureDevice lockForConfiguration:&error];
    if (!lockAcquired) {
        NSLog(@"锁定设备过程error，错误信息：%@",error.localizedDescription);
    }else{
        [_session beginConfiguration];
        propertyChange(captureDevice);
        [captureDevice unlockForConfiguration];
        [_session commitConfiguration];
    }
}
- (IBAction)paizhaoAction:(id)sender {
    AVCaptureConnection * videoConnection = [_output connectionWithMediaType:AVMediaTypeVideo];
    
    if (!videoConnection) {
//        NSLog(@"take photo failed!");
        return;
    }
    [_output captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
        if (imageDataSampleBuffer == NULL) {
            return;
        }
        NSData * imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
        UIImage * image = [UIImage imageWithData:imageData];
//        NSLog(@"image size = %@",NSStringFromCGSize(image.size));
        
        UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"KP"
                                                                     bundle:[NSBundle mainBundle]];
        PhotographCompleteVC *viewcv = [customerStoryboard instantiateViewControllerWithIdentifier:@"PhotographCompleteVC"];
        viewcv.superImg = image;
        viewcv.modalPresentationStyle= UIModalPresentationOverFullScreen;
        [self presentViewController:viewcv animated:YES completion:nil];
    }];
}
- (IBAction)backAction:(UIButton *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition) position {
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *device in devices) {
        if ([device position] == position) {
            return device;
        }
    }
    return nil;
}
- (AVCaptureDevice *)frontCamera {
    return [self cameraWithPosition:AVCaptureDevicePositionFront];
}

- (AVCaptureDevice *)backCamera {
    return [self cameraWithPosition:AVCaptureDevicePositionBack];
}


@end
